package com.example.demo.interceptor;

import com.example.demo.module.log.LogBean;
import com.example.demo.service.LogService;
import com.example.demo.util.GuidUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Arrays;
import java.util.Enumeration;

@Aspect
@Component
@Order(-1)
public class WebLogAspect {

    private Logger logger =  LoggerFactory.getLogger(this.getClass());

    @Autowired private LogService logService;

    /**
     * 定义一个切入点.
     * 解释下：
     *
     * ~ 第一个 * 代表任意修饰符及任意返回值.
     * ~ 第二个 * 任意包名
     * ~ 第三个 * 代表任意方法.
     * ~ 第四个 * 定义在web包或者子包
     * ~ 第五个 * 任意方法
     * ~ .. 匹配任意数量的参数.
     */
    @Pointcut("execution(public * com.example.demo.web..*.*(..))")
    public void webLog(){}

    private static String getHeader(HttpServletRequest request, String headName) {
        String value = request.getHeader(headName);
        return (!StringUtils.isEmpty(value) && !"unknown"
                .equalsIgnoreCase(value)) ? value : "";
    }

    @After("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable{

        // 接收到请求，记录请求内容
        logger.debug("WebLogAspect.doBefore()");
        ServletRequestAttributes attributes =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 记录下请求内容
        logger.debug("URL : " + request.getRequestURL().toString());
        logger.debug("HTTP_METHOD : " + request.getMethod());
        String ipFromNginx = getHeader(request, "X-Real-IP");
        logger.debug("ipFromNginx:" + ipFromNginx);
        logger.debug("IP : " + request.getRemoteAddr());
        logger.debug("CLASS_METHOD : " + joinPoint.getSignature().getDeclaringTypeName()+ "." + joinPoint.getSignature().getName());
        logger.debug("ARGS : " + Arrays.toString(joinPoint.getArgs()));
        //获取所有参数方法一：
        Enumeration<String> enu=request.getParameterNames();
        while(enu.hasMoreElements()){
            String paraName=(String)enu.nextElement();
            System.out.println(paraName+": "+request.getParameter(paraName));
        }
        ipFromNginx = StringUtils.isEmpty(ipFromNginx)?request.getRemoteAddr():ipFromNginx;

        String cs="";
        if(request.getQueryString()!=null){
            try {
                //将中文转码
                cs= URLDecoder.decode(request.getQueryString(),"utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        logService.add(new LogBean(GuidUtils.getUuid(),"11",request.getMethod(),ipFromNginx,request.getRequestURI(),cs));
    }

    @AfterReturning(returning = "ret", pointcut = "webLog()")
    public void doAfterReturning(Object ret){
        // 处理完请求，返回内容
        logger.debug("WebLogAspect.doAfterReturning()："+ret);
    }

}
